import { LoginForm } from '@features/LoginForm'
import { RegistrationForm } from '@features/RegistrationForm'
import { useI18n } from '@shared/lib/hooks/useI18n'
import { Button } from '@shared/ui/Button'
import { Popup } from '@shared/ui/Popup'
import { Toast } from '@shared/ui/Toast'
import classNames from 'classnames'
import { memo, useState } from 'react'
import { Zoom, toast } from 'react-toastify'
import RegistrationLoginFormSkeleton from './RegistrationLoginFormSkeleton/RegistrationLoginFormSkeleton'
import style from './RegistrationLoginForm.module.scss'

interface RegistrationLoginFormProps {
  className?: string
}

export const RegistrationLoginForm = memo(({ className }: RegistrationLoginFormProps) => {
  const [isActive, setIsActive] = useState(false)
  const [isRegistrationForm, setIsRegistrationForm] = useState(false)
  const { languageLoaded, t } = useI18n('auth')

  const openCloseModal = (isActive: boolean, isRegistrationForm?: boolean) => () => {
    setIsActive(isActive)
    setIsRegistrationForm(!!isRegistrationForm)
  }

  const onSuccessLogin = () => {
    setIsActive(false)
    toast(<Toast message='Пользователь вошел!' type='positive' />, { transition: Zoom })
  }

  const onSuccessRegistration = () => {
    setIsActive(false)
    toast(<Toast message='Пользователь зарегистрировался!' type='positive' />, { transition: Zoom })
  }

  return (
    <div className={classNames(style['registration-login-form'], className)}>
      {!languageLoaded ? (
        <RegistrationLoginFormSkeleton />
      ) : (
        <>
          <Button color='primary' filled onClick={openCloseModal(true)} size='large'>
            {t('sign_in')}
          </Button>
          <Button color='primary' filled onClick={openCloseModal(true, true)} size='large'>
            {t('sign_up')}
          </Button>
        </>
      )}
      <Popup centered isActive={isActive} onClose={openCloseModal(false)}>
        <div>
          {!isRegistrationForm && <LoginForm onSuccess={onSuccessLogin} />}
          {isRegistrationForm && <RegistrationForm onSuccess={onSuccessRegistration} />}
        </div>
      </Popup>
    </div>
  )
})
RegistrationLoginForm.displayName = 'RegistrationLoginForm'
